<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
    $('#date').datetimepicker({
        format: "YYYY-MM-DD"
    });
	$('#receivableTable').bootstrapTable({
		 
		  //请求方法
               method: 'get',
        height:550,
               //类型json
               dataType: "json",
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //显示详情按钮
    	       detailView: true,
    	       	//显示详细内容函数
	           detailFormatter: "detailFormatter",
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/fee/receivable/data1",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	edit(row.id);
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该应收记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/fee/receivable/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#receivableTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
               columns: [{
		        checkbox: true
		       
		    }
			,{
                       field: 'project',
                       title: '项目',
                       sortable: true
                       ,formatter:function(value, row , index){
                           return "<a href='javascript:edit(\""+row.id+"\")'>"+value+"</a>";
                       }
                   } ,{
                       field: 'status',
                       title: '状态',
                       sortable: true
                       ,formatter:function(value, row , index){
                           if(value=="1"){
                               return "已创建"
                           }else{
                               return "已确认"
                           }
                       }
                   }, {
                       field: 'received',
                       title: '已开票',
                       sortable: true
                       ,formatter:function(value, row , index){
                           if(value=="1"){
                               return "是"
                           }else{
                               return "否"
                           }
                       }
                   },{
                       field: 'shipmentNumbers',
                       title: '装运单号',
                       sortable: true


                   }
			,{
		        field: 'thdh',
		        title: '提货单号',
		        sortable: true
		       
		    }


                   ,{
                       field: 'start',
                       title: '起运地',
                       sortable: true

                   },{
                       field: 'arrive',
                       title: '结算地',
                       sortable: true

                   },{
                       field: 'width',
                       title: '结算吨位区间',
                       sortable: true

                   },{
                       field: 'price',
                       title: '单价',
                       sortable: true

                   },{
                       field: 'weight',
                       title: '总重量',
                       sortable: true

                   },{
                       field: 'company',
                       title: '收货单位',
                       sortable: true

                   },{
                       field: 'site',
                       title: '收货详细地址',
                       sortable: true

                   }


			,{
		        field: 'mileage',
		        title: '里程',
		        sortable: true
		       
		    }

                   ,{
                       field: 'surplus',
                       title: '结算金额(不含税)',
                       sortable: true

                   },{
                       field: 'sl',
                       title: '税率',
                       sortable: true

                   }
                   ,{
                       field: 'hs',
                       title: '结算金额(含税)',
                       sortable: true

                   }
                   ,{
                       field: 'ad',
                       title: '附加费用',
                       sortable: true

                   }
			,{
		        field: 'freight',
		        title: '总金额(含税)',
		        sortable: true
                       ,formatter:function(value, row , index){
		        	return value.toString().replace(/,/,"");
					   }
		    }
                   ,{
                       field: 'qr',
                       title: '受票方',
                       sortable: true

                   }
                   ,{
                       field: 'id',
                       title: '数据ID',
                       sortable: true

                   }
		     ]
		
		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#receivableTable').bootstrapTable("toggleView");
		}
	  
	  $('#receivableTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#receivableTable').bootstrapTable('getSelections').length);
            $('#edit').prop('disabled', ! $('#receivableTable').bootstrapTable('getSelections').length);
          $('#add').prop('disabled', $('#receivableTable').bootstrapTable('getSelections').length!=1);
          $('#qr').prop('disabled', $('#receivableTable').bootstrapTable('getSelections').length!=1);
          $('#qxqr').prop('disabled', $('#receivableTable').bootstrapTable('getSelections').length!=1);


      });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 1, 
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/fee/receivable/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe 
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#receivableTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		   $("#searchForm  .select-item").html("");
		  $('#receivableTable').bootstrapTable('refresh');
		});
		
		
	});
		
  function getIdSelections() {
        return $.map($("#receivableTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
function getjsje() {
    return $.map($("#receivableTable").bootstrapTable('getSelections'), function (row) {
        return row.freight
    });
}
function getzzl() {
    return $.map($("#receivableTable").bootstrapTable('getSelections'), function (row) {
        return row.weight
    });
}
function getstatus() {
    return $.map($("#receivableTable").bootstrapTable('getSelections'), function (row) {
        return row.status
    });
}
function getkp() {
    return $.map($("#receivableTable").bootstrapTable('getSelections'), function (row) {
        return row.received
    });
}
function qxqr() {
	var s=getkp();
	if(s=="1"){
		return;
	}
    jp.confirm('确定要取消确认该记录吗？', function(){
        $.ajax({
            url:'${ctx}/fee/receivable/qxqr?id='+getIdSelections(),
            success:function (data) {
                $('#receivableTable').bootstrapTable('refresh');
                jp.success("取消成功")
            }
        })})
}
function qr() {
    var status=getstatus();
    if(status!="1"){
        return;
    }
    jp.confirm('确定要确认该记录吗？', function(){
    $.ajax({
		url:'${ctx}/fee/receivable/qr?id='+getIdSelections(),
		success:function (data) {
            $('#receivableTable').bootstrapTable('refresh');
            jp.success("确认成功")
        }
	})})
}
  function deleteAll(){

		jp.confirm('确认要删除该应收记录吗？', function(){
			jp.loading();  	
			jp.get("${ctx}/fee/receivable/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#receivableTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})
          	   
		})
  }

function sk() {
    var status=getstatus();
    var kp=getkp();
    var s=status.toString().split(",");
    var k=kp.toString().split(",");
    var bol=false;
    var bo=false;
    for(var i=0;i<s.length;i++){
        if(s[i]=="1"){
            bol=true;
        }
    }
    for(var i=0;i<k.length;i++){
        if(k[i]=="1"){
            bo=true;
        }
    }
    if(bol||bo){
        return;
    }
    var z=getzzl();
    var je=z.toString().split(",");

    var j=getjsje();
    var jes=j.toString().split(",");
    var zje=0.0;
    var zzl=0.0;
    for(var i=0;i<jes.length;i++){
        zje+=parseFloat(jes[i].toString().replace(/,/,""));
        zzl+=parseFloat(je[i].toString().replace(/,/,""));
    }
    jp.openDialog('开票', "${ctx}/fee/js/form1?sy="+zje+"&w="+zzl+"&i="+getIdSelections(),'1000px', '800px', $('#receivableTable'));

}
  
  function qd() {
	  $.ajax({
		  url:"${ctx}/fee/receivable/qd?ids="+getIdSelections()+"&je="+$("#kpje").val(),
		  success:function (data) {
              $("#myModal").modal("hide");
              $('#receivableTable').bootstrapTable('refresh');
              jp.success("开票成功")
          }
		  
		  
	  })
  }
function fy() {
  	var status=getstatus();
  	if(status!="1"){
  		return;
	}
    jp.openDialog('添加附加费用', "${ctx}/fee/cost/form?i="+ getIdSelections(),'800px', '500px', $('#receivableTable'));
}
  function add(){
	  jp.openDialog('新增应收', "${ctx}/fee/receivable/form",'800px', '500px', $('#receivableTable'));
  }
  
  function edit(id){//没有权限时，不显示确定按钮
  	  if(id == undefined){
			id = getIdSelections();
		}
	   <shiro:hasPermission name="fee:receivable:edit">
	  jp.openDialogView('编辑应收', "${ctx}/fee/receivable/form?id=" + id,'1400px', '1200px', $('#receivableTable'));
	   </shiro:hasPermission>
	  <shiro:lacksPermission name="fee:receivable:edit">
	  jp.openDialogView('查看应收', "${ctx}/fee/receivable/form?id=" + id,'1400px', '1200px', $('#receivableTable'));
	  </shiro:lacksPermission>
  }
  
  
  
  
		   
  function detailFormatter(index, row) {
	  var htmltpl =  $("#receivableChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
	  var html = Mustache.render(htmltpl, {
			idx:row.id
		});
	  $.get("${ctx}/fee/receivable/detail?id="+row.id, function(receivable){
    	var receivableChild1RowIdx = 0, receivableChild1Tpl = $("#receivableChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data1 =  receivable.receivablesDetailedList;
		for (var i=0; i<data1.length; i++){
			addRow('#receivableChild-'+row.id+'-1-List', receivableChild1RowIdx, receivableChild1Tpl, data1[i]);
			receivableChild1RowIdx = receivableChild1RowIdx + 1;
		}
				
      	  			
      })
     
        return html;
    }
  
	function addRow(list, idx, tpl, row){
		$(list).append(Mustache.render(tpl, {
			idx: idx, delBtn: true, row: row
		}));
	}
			
</script>
<script type="text/template" id="receivableChildrenTpl">//<!--
	<div class="tabs-container">
		<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-{{idx}}-1" aria-expanded="true">应收明细</a></li>
		</ul>
		<div class="tab-content">
				 <div id="tab-{{idx}}-1" class="tab-pane fade in active">
						<table class="ani table">
						<thead>
							<tr>
								<th>物料</th>
								<th>结算系数</th>
								<th>里程</th>
								<th>重量</th>
								<th>运费</th>
								<th>备注信息</th>
							</tr>
						</thead>
						<tbody id="receivableChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
	</script>
	<script type="text/template" id="receivableChild1Tpl">//<!--
				<tr>
					<td>
						{{row.goods.name}}
					</td>
					<td>
						{{row.coefficient}}
					</td>
					<td>
						{{row.mileage}}
					</td>
					<td>
						{{row.weight}}
					</td>
					<td>
						{{row.freight}}
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
	</script>
